<?php


namespace App\Services;



use App\Models\HouseBroker;
use App\Models\LiveStreaming;
use App\Models\WxUser;
use App\Tools\CurlTools;
use App\Tools\JsonTools;
use App\Tools\JwtTools;
use App\Tools\NoteTools;

use App\Tools\RedisTools;
use Illuminate\Support\Facades\Log;

use Illuminate\Support\Facades\Redis;

class LoginServices
{
    /**
     * 静默登录
     * @param $code
     * @return array|string
     */

    public static function getToken($code){

        if (!$code){
            return JsonTools::JsonError([],2001,'code不能为空');
        }

        $loginUrl = sprintf(config('wxlogin.loginUrl'),config('wxlogin.AppID'),config('wxlogin.AppSecret'),$code);

        $codeResult = CurlTools::getUrl($loginUrl);

        $codeResult['im_id'] = md5($codeResult['openid']);

        $result = WxUser::where('openid',$codeResult['openid'])->first();
//        如果没有账号创建账号
        if (!$result){
            $result = WxUser::create($codeResult);
        }else{
            WxUser::where('id',$result['id'])->update($codeResult);
        }

        $token = JwtTools::gainToken($result['id']);

        return $token;
    }



    /**
     * 发送手机验证码
     * @param $phone
     * @return array
     */
    public static function sendNote($phone){

        $verificationCode = rand(100000,999999);
        $redis = RedisTools::getInstance()->connectRedis();
        if (!$phone){
            return JsonTools::JsonError([],2002,'手机号不能为空');
        }

//        redis缓存验证码
        $redis->setex('verificationCode'.$phone,300,$verificationCode);

        $number = $redis->get('verification'.$phone);

        if (!$number){
            $redis->setex('verification'.$phone,60,1);
        }else{
            $redis->incr('verification'.$phone,1);
            if ($number>=5){
                return JsonTools::JsonError([],2005,'请勿频繁发送验证码');
            }
        };

        $bool = NoteTools::noteSend($phone,$verificationCode);

        return $bool;
    }


    /**
     * 手机验证码登录
     */

    public static function loginPhone($phone,$verification){

        $redis = RedisTools::getInstance()->connectRedis();

        $verificationCode = $redis->get('verificationCode'.$phone);

        if ($verification!= $verificationCode){
            return JsonTools::JsonError([],2006,'验证码错误');
        }

        $user = HouseBroker::where('broker_phone',$phone)->first();

        if (empty($user)){
            return JsonTools::JsonError([],2003,'您不是经纪人');
        }

        $token = JwtTools::gainToken($user['id']);
//        获取是否有直播间
        $live = LiveStreaming::where('uid',$user['id'])->first();
        if ($live){
            $liveId =  $live['id'];
        }else{
            $liveId = 0;
        }
        $user = [
            "broker_name"=>$user['broker_name'],
            "broker_image"=>$user['broker_image'],
            "token"=>$token,
            'id'=>$liveId,
            'new_house'=>$user['new_house'],
            'two_house'=>$user['two_house'],
            'rental_housing'=>$user['rental_housing']
        ];
        return JsonTools::JsonSuccess($user,200,'登陆成功');
    }

    /**
     * 微信授权登录
     */


    public static function wxLogin($code,$nickName,$headPortrait){

        if (!$code){
            return JsonTools::JsonError([],2001,'code不能为空');
        }

        $loginUrl = sprintf(config('wxlogin.loginUrl'),config('wxlogin.AppID'),config('wxlogin.AppSecret'),$code);

        $codeResult = CurlTools::getUrl($loginUrl);

        $codeResult['im_id'] = md5($codeResult['openid']);

        $result = WxUser::where('openid',$codeResult['openid'])->first();

        $IM = new IMServices();

//        判断是否有用户，没有用户创建用户

        if (!$result){
            $result = WxUser::create($codeResult);
        }else{
            WxUser::where('id',$result['id'])->update($codeResult);
            wxUser::where('id',$result['id'])->update([
                'user_name'=>$nickName,
                'user_image'=>$headPortrait,
            ]);

            $result = WxUser::where('openid',$codeResult['openid'])->first();
//        创建IM账号
            $IM->accountImport($result);
        }

        $token = JwtTools::gainToken($result['id']);

        $live = LiveStreaming::where('uid',$result['id'])->first();
        if ($live){
            $liveId =  $live['id'];
        }else{
            $liveId = 0;
        }
        $user = [
            "nickname"=>$result['user_name'],
            "user_image"=>$result['user_image'],
            "im_id"=>$result['im_id'],
            "token"=>$token,
            'id'=>$liveId
        ];
        return $user;

    }
}
